package cn.maidouya.order.service.impl;

import cn.maidouya.basic.util.CodeGenerateUtils;
import cn.maidouya.basic.util.PageList;
import cn.maidouya.order.domain.AdoptOrder;
import cn.maidouya.basic.service.impl.BaseServiceImpl;
import cn.maidouya.order.domain.OrderAddress;
import cn.maidouya.order.mapper.AdoptOrderMapper;
import cn.maidouya.order.mapper.OrderAddressMapper;
import cn.maidouya.order.query.AdoptOrderQuery;
import cn.maidouya.order.service.IAdoptOrderService;
import cn.maidouya.org.domain.Employee;
import cn.maidouya.org.mapper.EmployeeMapper;
import cn.maidouya.pay.constants.OrderConstants;
import cn.maidouya.pay.domain.PayBill;
import cn.maidouya.pay.mapper.PayBillMapper;
import cn.maidouya.pay.service.IPayBillService;
import cn.maidouya.pay.service.impl.PayBillServiceImpl;
import cn.maidouya.pet.domain.Pet;
import cn.maidouya.pet.mapper.PetMapper;
import cn.maidouya.quartz.constants.QuartzConstants;
import cn.maidouya.quartz.jobs.QuartzJobInfo;
import cn.maidouya.quartz.service.IQuartzService;
import cn.maidouya.user.domain.Logininfo;
import cn.maidouya.user.domain.User;
import cn.maidouya.user.domain.UserAddress;
import cn.maidouya.user.mapper.UserAddressMapper;
import cn.maidouya.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {
    @Autowired// 宠物
    private PetMapper petMapper;
    @Autowired// 用户
    private UserMapper userMapper;
    @Autowired// 领养保存订单
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired// 用户保存的地址
    private UserAddressMapper userAddressMapper;
    @Autowired// 领养保存地址
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;
    /**
     *    领养订单
     * @param params  订单操作
     * @param logininfo 当前登录人
     * @return
     */
    @Override
    public String submit(Map<String, Object> params, Logininfo logininfo) {
        // 获取前台数据 宠物id  宠物支付方式  宠物地址(配送地址)  服务方式(快递方式)
        Long petId = Long.valueOf(params.get("pet_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());

        // 1. 修改订单为下架
        Pet pet = petMapper.loadById(petId);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
            if (pet != null){
                pet.setState(0);
                pet.setOffsaletime(new Date());
                // 2. 绑定领养人
                pet.setUser_id(user.getId());
                petMapper.update(pet);
            }

        // 3. 生成订单  Alt + Shift + m
        AdoptOrder order = initAdoptOrder(pet);
        String unionPaySn = CodeGenerateUtils.generateUnionPaySn();
        order.setPaySn(unionPaySn);
        adoptOrderMapper.save(order);

        // 4. 生成订单地址
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);

        // 5. 生成支付订单
        PayBill bill = new PayBill();
            bill.setDigest(order.getDigest());  // 订单摘要
            bill.setMoney(order.getPrice());  // 订单价格
            bill.setUnionPaySn(order.getPaySn());  // 统一支付单
            bill.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.ORDER_TIMEOUT));  // 最后确认时间
            bill.setPayChannel(payMethod);  // 支付方式
            bill.setBusinessType(OrderConstants.BUSINESS_TYPE_ACQUISITION_ORDER); // 订单类型
            bill.setBusinessKey(order.getId()); // 订单业务id
            bill.setUser_id(user.getId());  // 领养用户商品
            bill.setShop_id(pet.getShop_id());  // 店铺id
            bill.setNickName(user.getUsername());  // 用户昵称
        payBillMapper.save(bill);

        // 6.  订单定时取消
        QuartzJobInfo quartzJob = new QuartzJobInfo();
                String jobName = QuartzConstants.ORDER_PRODUCT_CANCEL_PREFIX + order.getPaySn(); //  拼接定时器名称
                quartzJob.setJobName(jobName); // 定时取消名称
                quartzJob.setType(QuartzConstants.ORDER_ADOPT_TYPE_CANCEL); // 定时器类型
                quartzJob.setFireDate(order.getLastPayTime()); // 最后确认时间
                Map<String, Object> mapQuartz = new HashMap<String, Object>();
                mapQuartz.put("orderId",order.getId());
                quartzJob.setParams(mapQuartz); // 设置参数
                //  添加超时未支付取消定时任务
        quartzService.addJob(quartzJob);
        System.err.println(order.getDigest() + "添加定时成功");

        //  7. 调用统一支付接口、返回同步信息给前端(扫码界面)
        return payBillService.pay(bill);
    }

    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        // 订单信息拷贝到订单地址
        BeanUtils.copyProperties(userAddress,orderAddress);
        // 设置为null，不然会被覆盖id值
        orderAddress.setId(null);
        // 订单编号id值
        orderAddress.setOrder_id(order.getId());
        // 订单编号
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Pet pet) {
        AdoptOrder order = new AdoptOrder();
        // 宠物名称
        order.setDigest("摘要"+pet.getName()+"的领养订单");
        // 宠物金额
        order.setPrice(pet.getSaleprice());
        // 生成订单编号
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getId());
        order.setOrderSn(orderSn);
        // 最后确定下单时间
        order.setLastPayTime(new Date(System.currentTimeMillis()+OrderConstants.ORDER_TIMEOUT));
        // 宠物id
        order.setPet_id(pet.getId());
        // 用户id
        order.setUser_id(pet.getId());
        // 店铺id
        order.setShop_id(pet.getShop_id());
        return order;
    }

    // 后台：平台和店铺管理员查询订单
    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, Long logininfoId) {
        Employee employee = employeeMapper.loadByLogininfoId(logininfoId);
        if (employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryData(query);
    }

    // 前台：用户查询订单
    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, Long logininfoId) {
        User user = userMapper.loadByLogininfoId(logininfoId);
        if (user != null){
            query.setUserId(user.getId());
        }
        return super.queryData(query);
    }
    // quartz触发的定时取消任务
    @Override
    public void quartzCancel(Long orderId) {
    // 1. 修改领养订单状态
        AdoptOrder adoptOrder = adoptOrderMapper.loadById(orderId);
        adoptOrder.setState(-1);
        adoptOrderMapper.update(adoptOrder);
        System.out.println("订单被自动取消");
        // 2. 修改支付单状态
        String paySn = adoptOrder.getPaySn();
        PayBill payBill = payBillMapper.loadByUnionPaySn(paySn);
        payBill.setState(-1);
        payBillMapper.update(payBill);
        System.out.println(adoptOrder.getDigest() +"订单被自动取消");
    }
}